package ldh.im.admin.rest;

import ldh.common.mvc.DateEditor;
import ldh.im.base.pojo.ImGroup;
import ldh.im.base.pojo.ImUser;
import ldh.im.base.service.ImGroupService;
import ldh.im.base.service.ImUserService;
import ldh.im.admin.ResponseResult;
import ldh.im.admin.dto.FxUserDto;
import ldh.im.admin.validate.ParamCheckUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/client")
public class UserInfoController {

    @Resource
    private ImUserService imUserService;
    @Resource
    private ImGroupService imGroupService;

    @InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
        //对于需要转换为Date类型的属性，使用DateEditor进行处理
        binder.registerCustomEditor(Date.class, new DateEditor("yyyy-MM-dd"));
    }

    @GetMapping(path="/getChangeFreights")
    public ResponseResult getChangeFreights(@RequestParam("userId")Long userId, @RequestParam("tenantCode")String tenantCode,
                                            @RequestParam(name="changeDate", defaultValue = "2021-01-01") Date changeDate) {
        ImUser imUser = imUserService.getByIdAndTenantCode(userId, tenantCode);
        ParamCheckUtil.notNull(imUser, "参数不能为空");

        List<ImGroup> changeGroups = imGroupService.getAllChangeImGroups(imUser, changeDate);
        List<ImUser> changeUsers = imUserService.getAllChangeImUsers(imUser, changeDate);
        filterData(changeGroups); // 去掉敏感数据
        List<FxUserDto> userDtoes = changeUsers.stream().map(this::userToDto).collect(Collectors.toList());
        return ResponseResult.build().put("users", userDtoes).put("groups", changeGroups);
    }

    @GetMapping(path="/test")
    public ResponseResult test() {
        return ResponseResult.build().put("users", "").put("groups", "");
    }

    private void filterData(List<ImGroup> changeGroups) {
        changeGroups.forEach(g->{
            g.setCreateTime(null);
            g.setTenantCode(null);
            g.setId(null);
        });
    }

    private FxUserDto userToDto(ImUser user) {
        FxUserDto userDto = new FxUserDto();
        BeanUtils.copyProperties(user, userDto);
        return userDto;
    }
}
